package com.yms.tree;

import java.util.TreeMap;
import java.util.TreeSet;

/**
 * @version : 1.0
 * @author: yangmingsong
 * @date: 2022/9/8-09-08-9:40
 * @description: spring5-test
 */
public class Test {

    public static void main(String[] args) {
        Tree root = new Tree();
        root.add(2);
        root.add(1);
    }

}
class Tree{

    private int data;
    private Tree root,Lchild;
    private Tree Rchild;
    private int size;

    public Tree(){
    }
    public Tree(int e){
        this.data = e;
    }

    public boolean add(int data) {
        Tree newNode = new Tree(data);
        if(newNode == null){//当前树为空树，没有任何节点
            root = newNode;
            size++;
            return true;
        }else{
            Tree current = root;
            Tree parentNode = null;
            while(current != null){
                parentNode = current;
                if(current.data > data){//当前值比插入值大，搜索左子节点
                    current = current.Lchild;
                    if(current == null){//左子节点为空，直接将新值插入到该节点
                        newNode.root = parentNode;
                        parentNode.Lchild = newNode;
                        size++;
                        return true;
                    }
                }else{
                    current = current.Rchild;
                    if(current == null){//右子节点为空，直接将新值插入到该节点
                        newNode.root = parentNode;
                        parentNode.Rchild = newNode;
                        size++;
                        return true;
                    }
                }
            }
        }
        return false;
    }

    public void preOrder(Tree e){
        Tree temp = root;
        if(size!=0){
            System.out.println(root.data);
            if(root.Lchild!=null){
                temp = root.Lchild;
                preOrder(temp);
            }else {
                System.out.println(root.data);
            }
        }
    }

    public Tree getRoot(Tree e){
        return e==null?root:e.root;
    }
}